<template>
  <div class="login">
    <header>UNI-ADMIN</header>
    <el-form :model="user" ref="loginForm" :rules="rules">
      <el-form-item prop="username">
        <el-input placeholder="请输入用户名" v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input placeholder="密码" v-model="user.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" style="width:100%;" :loading="loading" @click="goLogin">
          {{loading ? "登陆中..." : "立即登录"}}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  // 组件名称
  name: "",
  // 组件参数 接收来自父组件的数据
  props: [],
  // 局部注册的组件
  components: {},
  // 组件状态值
  data() {
    return {
      loading:false,
      user: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    // 登录操作
    goLogin() {
      this.$refs["loginForm"].validate(valid => {
        if (valid) {
          this.loading = true; //校验成功登录按钮出现loading效果
          // 调用登录接口信息
          this.$axios
            .post("/admin/login", this.user)
            .then(res => {
              this.loading = false ; // 登录成功登录按钮关闭loading效果
              // 登录成功后执行
              console.log(res.data.token);
              this.$message.success("登陆成功");
              // 存储用户登录成功的信息
              let obj = { 
                  token:res.data.token,
                  username:res.data.username,
              }
              this.$store.commit("goLogin",obj);
              // 登录成功进行跳转 
              this.$router.push("/admin/home"); 
            })
            .catch(error => {
               this.loading = false ;//登陆失败停止loading效果
              // 登陆失败后执行
              console.log(error.response.data);
              // 弹出错误提示
              this.$message.error(error.response.data.msg)
              return false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  },
  mounted() {}
};
</script>

<style  lang="scss" scoped>
.login {
  width: 30%;
  border: 1px solid #dddddd;
  border-radius: 5px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -60%);
  header {
    width: 100%;
    line-height: 50px;
    text-align: center;
    font-weight: bold;
    border-bottom: 1px #dddddd solid;
  }
  .el-form {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
  }
}
</style>
